<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Example: Rebuilding Class Instances from JSON Data</title>
    <link rel="stylesheet" href="http://yui.yahooapis.com/3.4.0pr3/build/cssgrids/grids-min.css">
    <link rel="stylesheet" href="../assets/css/main.css">
    <link rel="stylesheet" href="../assets/vendor/prettify/prettify-min.css">
    <script src="../../build/yui/yui-min.js"></script>
</head>
<body>

<div id="doc">
    <h1>Example: Rebuilding Class Instances from JSON Data</h1>

    

    <div class="yui3-g">
        <div id="main" class="yui3-u">
            <div class="content"><div class="intro">
    <p>This example illustrates one method of serializing and recreating class instances by using the <code>replacer</code> and <code>reviver</code> parameters to <code>JSON.stringify</code> and <code>JSON.parse</code> respectively.</p>
</div>

<div class="example yui3-skin-sam">
    <style scoped>
#demo pre {
    background: #fff;
    border: 1px solid #ccc;
    margin: 1em;
    padding: 1em;
    white-space: pre-wrap; /* css-3 */
    word-wrap: break-word; /* Internet Explorer 5.5+ */
}
</style>

<div id="demo">
    <input type="button" id="demo_freeze" value="Freeze">
    <input type="button" id="demo_thaw" disabled="disabled" value="Thaw">
    <pre id="demo_frozen">(stringify results here)</pre>
    <div id="demo_thawed"></div>
</div>

<script type="text/javascript">
YUI().use("node", "json", function(Y) {

var example = {
    data       : null,
    jsonString : null,

    dateRE : /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d+)?Z$/,

    cryo : function (k,o) {
        return (o instanceof CaveMan) ? CaveMan.freeze(o) : o;
    },
    revive : function (k,v) {
        // Turn anything that looks like a UTC date string into a Date instance
        var match = Y.Lang.isString(v) ? v.match(example.dateRE) : null,
            d;

        if (match) {
            d = new Date();
            d.setUTCFullYear(match[1], (match[2] - 1), match[3]);
            d.setUTCHours(match[4], match[5], match[6]);
            return d;
        }
        // Check for cavemen by the _class key
        if (v instanceof Object && v._class == 'CaveMan') {
            return CaveMan.thaw(v);
        }
        // default to returning the value unaltered
        return v;
    }
};

function CaveMan(name,discovered) {
    this.name       = name;
    this.discovered = discovered;
};
CaveMan.prototype.getName = function () {
    return this.name + ", the cave man";
}

// Static methods to convert to and from a basic object structure
CaveMan.thaw = function (o) {
    return new CaveMan(o.n, o.d);
};
// Convert to a basic object structure including a class identifier
CaveMan.freeze = function (cm) {
    return {
        _class : 'CaveMan',
        n : cm.name,
        d : cm.discovered // remains a Date for standard JSON serialization
    };
};

example.data    = {
    count : 1,
    type  : 'Hominid',
    specimen : [
        new CaveMan('Ed',new Date(1946,6,6))
    ]
};

Y.one('#demo_freeze').on('click',function (e) {
    // Format the string with 4 space indentation
    example.jsonString = Y.JSON.stringify(example.data, example.cryo, 4);

    Y.one('#demo_frozen').set('text', example.jsonString);
    Y.one('#demo_thaw').set('disabled',false);
});

Y.one('#demo_thaw').on('click',function (e) {
    var parsedData = Y.JSON.parse(example.jsonString, example.revive);
        cm = parsedData.specimen[0];

    Y.one('#demo_thawed').set('innerHTML',
        "<p>Specimen count: " + parsedData.count + "</p>"+
        "<p>Specimen type: " + parsedData.type + "</p>"+
        "<p>Instanceof CaveMan: " + (cm instanceof CaveMan) + "</p>"+
        "<p>Name: " + cm.getName() + "</p>"+
        "<p>Discovered: " + cm.discovered + "</p>");
});

// Expose the example objects for inspection
example.CaveMan = CaveMan;
YUI.example = example;

});
</script>

</div>

<h3>The CaveMan class</h3>
<p>For this example, we'll use a class CaveMan, with a property <code>discovered</code> that holds a <code>Date</code> instance, and a method <code>getName</code>.</p>

<pre class="code prettyprint">YUI().use(&quot;node&quot;, &quot;json&quot;, function(Y) {

function CaveMan(name,discovered) {
    this.name       = name;
    this.discovered = discovered;
};
CaveMan.prototype.getName = function () {
    return this.name + &quot;, the cave man&quot;;
}

...</pre>


<h3>Add <code>freeze</code> and <code>thaw</code> static methods</h3>
<p>We'll add the methods responsible for serializing and reconstituting instances to the CaveMan class as static methods.</p>

<pre class="code prettyprint">&#x2F;&#x2F; Static method to convert to a basic structure with a class identifier
CaveMan.freeze = function (cm) {
    return {
        _class : &#x27;CaveMan&#x27;,
        n : cm.name,
        d : cm.discovered &#x2F;&#x2F; remains a Date for standard JSON serialization
    };
};

&#x2F;&#x2F; Static method to reconstitute a CaveMan from the basic structure
CaveMan.thaw = function (o) {
    return new CaveMan(o.n, o.d);
};</pre>


<h3>Reference the methods in replacer and reviver functions</h3>
<p>We'll create an <code>example</code> namespace to hold our moving parts.  In it, we'll add a method to pass to <code>JSON.stringify</code> that calls our custom serializer, and another method to pass to <code>JSON.parse</code> that detects the serialized structure and calls our thawing method.</p>

<pre class="code prettyprint">var example = {
    cryo : function (k,o) {
        return (o instanceof CaveMan) ? CaveMan.freeze(o) : o;
    },

    revive : function (k,v) {
        &#x2F;&#x2F; Check for cavemen by the _class key
        if (v instanceof Object &amp;&amp; v._class == &#x27;CaveMan&#x27;) {
            return CaveMan.thaw(v);
        }
        &#x2F;&#x2F; default to returning the value unaltered
        return v;
    }
};</pre>


<h3>The data to be serialized</h3>
<p>We'll create a CaveMan instance and nest it in another object structure to illustrate how the thawing process still operates normally for all other data.</p>
<pre class="code prettyprint">example.data = {
    count : 1,
    type  : &#x27;Hominid&#x27;,
    specimen : [
        new CaveMan(&#x27;Ed&#x27;,new Date(1946,6,6))
    ]
};</pre>


<h3>Thawing from the inside out and the <code>Date</code> instance</h3>
<p>The reviver function passed to <code>JSON.parse</code> is applied to all key:value pairs in the raw parsed object from the deepest keys to the highest level.  In our case, this means that the <code>name</code> and <code>discovered</code> properties will be passed through the reviver, and <em>then</em> the object containing those keys will be passed through.</p>
<p>We'll take advantage of this by watching for UTC formatted date strings (the default JSON serialization for Dates) and reviving them into proper <code>Date</code> instances before the containing object gets its turn in the reviver.</p>

<pre class="code prettyprint">var example = {
    dateRE : &#x2F;^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d+)?Z$&#x2F;,

    cryo : function (k,o) {
        return (o instanceof CaveMan) ? CaveMan.freeze(o) : o;
    },
    revive : function (k,v) {
        &#x2F;&#x2F; Turn anything that looks like a UTC date string into a Date instance
        var match = Y.Lang.isString(v) ? v.match(example.dateRE) : null,
            d;

        if (match) {
            d = new Date();
            d.setUTCFullYear(match[1], (match[2] - 1), match[3]);
            d.setUTCHours(match[4], match[5], match[6]);
            return d;
        }
        &#x2F;&#x2F; Check for cavemen by the _class key
        if (v instanceof Object &amp;&amp; v._class == &#x27;CaveMan&#x27;) {
            return CaveMan.thaw(v);
        }
        &#x2F;&#x2F; default to returning the value unaltered
        return v;
    }
};</pre>


<p>Now when the reviver function is evaluating the object it determines to be a CaveMan, the <code>discovered</code> property is correctly containing a <code>Date</code> instance.</p>

<h3>Choose your serialization</h3>
<p>You'll note there are two freeze and thaw operations going on in this example.  One for our CaveMan class and one for <code>Date</code> instances.  Their respective serialization and recreation techniques are very different.  You are free to decide the serialized format of your objects.  Choose whatever makes sense for your application.</p>
<p><em>Note</em>: There is no explicit <code>Date</code> serialization method listed inline because <code>JSON</code> natively supports <code>Date</code> serialization.   However, it is outside the scope of the parser's duty to create Date instances, so it's up to you to recreate them in the <code>parse</code> phase.  Feel free to use the method included here.</p>

<h3>Show and Tell</h3>
<p>Now we add the event handlers to the example buttons to call <code>JSON.stringify</code> and <code>parse</code> with our <code>example.cryo</code> and <code>example.revive</code> methods, respectively.</p>

<pre class="code prettyprint">Y.one(&#x27;#demo_freeze&#x27;).on(&#x27;click&#x27;,function (e) {
    example.jsonString = Y.JSON.stringify(example.data, example.cryo);

    Y.one(&#x27;#demo_frozen&#x27;).set(&#x27;innerHTML&#x27;, example.jsonString);
    Y.one(&#x27;#demo_thaw&#x27;).set(&#x27;disabled&#x27;,false);
});

Y.one(&#x27;#demo_thaw&#x27;).on(&#x27;click&#x27;,function (e) {
    var x  = Y.JSON.parse(example.jsonString, example.revive);
        cm = x.specimen[0];

    Y.one(&#x27;#demo_thawed&#x27;).set(&#x27;innerHTML&#x27;,
        &quot;&lt;p&gt;Specimen count: &quot; + x.count + &quot;&lt;&#x2F;p&gt;&quot;+
        &quot;&lt;p&gt;Specimen type: &quot; + x.type + &quot;&lt;&#x2F;p&gt;&quot;+
        &quot;&lt;p&gt;Instanceof CaveMan: &quot; + (cm instanceof CaveMan) + &quot;&lt;&#x2F;p&gt;&quot;+
        &quot;&lt;p&gt;Name: &quot; + cm.getName() + &quot;&lt;&#x2F;p&gt;&quot;+
        &quot;&lt;p&gt;Discovered: &quot; + cm.discovered + &quot;&lt;&#x2F;p&gt;&quot;);
});

}); &#x2F;&#x2F; end of YUI(..).use(.., function (Y) {</pre>


<h3>Full Code Listing</h3>

<pre class="code prettyprint">&lt;style scoped&gt;
#demo pre {
    background: #fff;
    border: 1px solid #ccc;
    margin: 1em;
    padding: 1em;
    white-space: pre-wrap; &#x2F;* css-3 *&#x2F;
    word-wrap: break-word; &#x2F;* Internet Explorer 5.5+ *&#x2F;
}
&lt;&#x2F;style&gt;

&lt;div id=&quot;demo&quot;&gt;
    &lt;input type=&quot;button&quot; id=&quot;demo_freeze&quot; value=&quot;Freeze&quot;&gt;
    &lt;input type=&quot;button&quot; id=&quot;demo_thaw&quot; disabled=&quot;disabled&quot; value=&quot;Thaw&quot;&gt;
    &lt;pre id=&quot;demo_frozen&quot;&gt;(stringify results here)&lt;&#x2F;pre&gt;
    &lt;div id=&quot;demo_thawed&quot;&gt;&lt;&#x2F;div&gt;
&lt;&#x2F;div&gt;

&lt;script type=&quot;text&#x2F;javascript&quot;&gt;
YUI().use(&quot;node&quot;, &quot;json&quot;, function(Y) {

var example = {
    data       : null,
    jsonString : null,

    dateRE : &#x2F;^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d+)?Z$&#x2F;,

    cryo : function (k,o) {
        return (o instanceof CaveMan) ? CaveMan.freeze(o) : o;
    },
    revive : function (k,v) {
        &#x2F;&#x2F; Turn anything that looks like a UTC date string into a Date instance
        var match = Y.Lang.isString(v) ? v.match(example.dateRE) : null,
            d;

        if (match) {
            d = new Date();
            d.setUTCFullYear(match[1], (match[2] - 1), match[3]);
            d.setUTCHours(match[4], match[5], match[6]);
            return d;
        }
        &#x2F;&#x2F; Check for cavemen by the _class key
        if (v instanceof Object &amp;&amp; v._class == &#x27;CaveMan&#x27;) {
            return CaveMan.thaw(v);
        }
        &#x2F;&#x2F; default to returning the value unaltered
        return v;
    }
};

function CaveMan(name,discovered) {
    this.name       = name;
    this.discovered = discovered;
};
CaveMan.prototype.getName = function () {
    return this.name + &quot;, the cave man&quot;;
}

&#x2F;&#x2F; Static methods to convert to and from a basic object structure
CaveMan.thaw = function (o) {
    return new CaveMan(o.n, o.d);
};
&#x2F;&#x2F; Convert to a basic object structure including a class identifier
CaveMan.freeze = function (cm) {
    return {
        _class : &#x27;CaveMan&#x27;,
        n : cm.name,
        d : cm.discovered &#x2F;&#x2F; remains a Date for standard JSON serialization
    };
};

example.data    = {
    count : 1,
    type  : &#x27;Hominid&#x27;,
    specimen : [
        new CaveMan(&#x27;Ed&#x27;,new Date(1946,6,6))
    ]
};

Y.one(&#x27;#demo_freeze&#x27;).on(&#x27;click&#x27;,function (e) {
    &#x2F;&#x2F; Format the string with 4 space indentation
    example.jsonString = Y.JSON.stringify(example.data, example.cryo, 4);

    Y.one(&#x27;#demo_frozen&#x27;).set(&#x27;text&#x27;, example.jsonString);
    Y.one(&#x27;#demo_thaw&#x27;).set(&#x27;disabled&#x27;,false);
});

Y.one(&#x27;#demo_thaw&#x27;).on(&#x27;click&#x27;,function (e) {
    var parsedData = Y.JSON.parse(example.jsonString, example.revive);
        cm = parsedData.specimen[0];

    Y.one(&#x27;#demo_thawed&#x27;).set(&#x27;innerHTML&#x27;,
        &quot;&lt;p&gt;Specimen count: &quot; + parsedData.count + &quot;&lt;&#x2F;p&gt;&quot;+
        &quot;&lt;p&gt;Specimen type: &quot; + parsedData.type + &quot;&lt;&#x2F;p&gt;&quot;+
        &quot;&lt;p&gt;Instanceof CaveMan: &quot; + (cm instanceof CaveMan) + &quot;&lt;&#x2F;p&gt;&quot;+
        &quot;&lt;p&gt;Name: &quot; + cm.getName() + &quot;&lt;&#x2F;p&gt;&quot;+
        &quot;&lt;p&gt;Discovered: &quot; + cm.discovered + &quot;&lt;&#x2F;p&gt;&quot;);
});

&#x2F;&#x2F; Expose the example objects for inspection
example.CaveMan = CaveMan;
YUI.example = example;

});
&lt;&#x2F;script&gt;</pre>

</div>
        </div>

        <div id="sidebar" class="yui3-u">
            

            
                <div class="sidebox">
                    <div class="hd">
                        <h2 class="no-toc">Examples</h2>
                    </div>

                    <div class="bd">
                        <ul class="examples">
                            
                                
                                    <li data-description="Use JSON to parse data received via XMLHttpRequest via Y.io calls — a simple JSON use case.">
                                        <a href="json-connect.html">JSON with Y.io</a>
                                    </li>
                                
                            
                                
                                    <li data-description="Use the replacer and reviver parameters to reconstitute object instances that have been serialized to JSON.">
                                        <a href="json-freeze-thaw.html">Rebuilding Class Instances from JSON Data</a>
                                    </li>
                                
                            
                                
                                    <li data-description="Use a currency conversion calculation to add a new price member to a JSON response, demonstrating how JSON data, once retrieved, can be transformed during parsing.">
                                        <a href="json-convert-values.html">Adding New Object Members During Parsing</a>
                                    </li>
                                
                            
                                
                            
                        </ul>
                    </div>
                </div>
            

            
                <div class="sidebox">
                    <div class="hd">
                        <h2 class="no-toc">Examples That Use This Component</h2>
                    </div>

                    <div class="bd">
                        <ul class="examples">
                            
                                
                            
                                
                            
                                
                            
                                
                                    <li data-description="Portal style example using Drag &amp; Drop Event Bubbling and Animation.">
                                        <a href="../dd/portal-drag.html">Portal Style Example</a>
                                    </li>
                                
                            
                        </ul>
                    </div>
                </div>
            
        </div>
    </div>
</div>

<script src="../assets/vendor/prettify/prettify-min.js"></script>
<script>prettyPrint();</script>

</body>
</html>
